<template>
  <div>
    <el-tree
      id="tree"
      :data="departmentList"
      :props="{
        children: 'children',
        label: 'name'
      }"
      default-expand-all
    >
      <template slot-scope="{ data }">
        <div class="node-container">
          <div class="node-name">{{ data.name }}</div>
          <div class="node-leader">{{ data.manager }}</div>
          <el-dropdown
            class="node-operator"
            trigger="click"
            @click.native="e => e.stopPropagation()"
            @command="(cmd) => onOperatorSelect(cmd, data.id)"
          >
            <span>
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="add">添加子部门</el-dropdown-item>
              <el-dropdown-item v-if="data.pid !== '-1'" command="edit">编辑部门</el-dropdown-item>
              <el-dropdown-item v-if="data.pid !== '-1'" command="remove">删除部门</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </template>
    </el-tree>

    <button @click="createPDF">生成PDF</button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { getTreeData } from '@/utils';
import html2pdf from 'html2pdf.js';

export default {
  computed: {
    ...mapState({
      // departmentList: state => getTreeData(state.departmentList),
      departmentList: state => {
        const grandParent = state.departmentList.find(d => d.pid === '-1');
        if (!grandParent) {
          return [];
        }
        grandParent.manager = '负责人';
        const correctDepartmentList = state.departmentList.map(d => {
          if (!d.pid) {
            d.pid = grandParent.id;
          }
          return d;
        })
        return getTreeData(correctDepartmentList, '-1');
      },
    }),
  },
  methods: {
    ...mapActions([
      'updateDepartmentList'
    ]),
    // 生成PDF
    createPDF () {
      html2pdf(document.querySelector('#tree'));
    },
    onOperatorSelect (cmd, id) {
      switch (cmd) {
        case 'add':
          this.onAdd(id);
          break;
        case 'edit':
          this.onEdit(id);
          break;
        case 'remove':
          this.onRemove(id);
          break;

        default:
          break;
      }
    },
    onAdd (id) {
      console.log(id);
    },
    onEdit (id) {

    },
    onRemove (id) {

    },
  },
  async created () {
    await this.updateDepartmentList();
  }
}
</script>

<style lang="scss" scoped>
.node-container {
  display: flex;
  width: 100%;

  .node-name {
    flex: 1;
  }

  .node-leader {
    width: 100px;
  }

  .node-operator {
    width: 100px;
  }
}
</style>
